package com.gqyin.demo.exception;

import com.gqyin.demo.common.CommonResult;
import com.gqyin.demo.common.ResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * @author guiqing.yin
 * 2024-03-28 16:03
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    public static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public CommonResult<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        StringBuilder errorMessage = new StringBuilder();
        fieldErrors.forEach(error -> errorMessage.append(error.getDefaultMessage()).append(". "));
        return CommonResult.error(ResponseCode.ILLEGAL_PARAM, errorMessage.toString());
    }

    @ExceptionHandler(TestException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResult<String> handleTestExceptions(TestException ex) {
        LOGGER.error(ex.getMessage(), ex);
        return CommonResult.error(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResult<String> handleExceptions(Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return CommonResult.error(ex.getMessage());
    }
}
